package com.wuliu.driver.util;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.codehaus.jettison.json.JSONArray;
import org.codehaus.jettison.json.JSONObject;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Component
public class MapUtil {
    private static final String GAODE_API_KEY = "a2b6275dc0cc92d483a3cb8478d60f33";
    private static final String REVERSE_GEOCODING_URL = "https://restapi.amap.com/v3/geocode/regeo";
    private static final String GEOCODING_URL = "https://restapi.amap.com/v3/geocode/geo";
    //根据经纬度获取地址
    public String parseResult(double latitude, double longitude) throws IOException {
        System.out.println("latitude:"+latitude+"longitude:"+longitude);
        OkHttpClient client = new OkHttpClient();

        String url = String.format("%s?location=%.6f,%.6f&output=json&key=%s",
                REVERSE_GEOCODING_URL, longitude, latitude, GAODE_API_KEY);

        Request request = new Request.Builder()
                .url(url)
                .build();
        String jsonResult = "";
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            jsonResult= response.body().string();
        }
        try {
            JSONObject jsonObject = new JSONObject(jsonResult);
            int status = jsonObject.optInt("status");
            if (status == 1) { // 成功

                JSONObject regeocode = jsonObject.getJSONObject("regeocode");
                JSONObject addressComponent = regeocode.getJSONObject("addressComponent");
                System.out.println("Address Component:"+addressComponent);
                String formattedAddress = regeocode.getString("formatted_address");
                String province = addressComponent.getString("province");
                String city = addressComponent.getString("city");
                String district = addressComponent.getString("district");
                String town = addressComponent.getString("township");

                String[] split = formattedAddress.split("省");

                return formattedAddress;
            } else {
                System.out.println("Error: " + jsonObject.optString("info"));
                return "获取失败";
            }
        } catch (Exception e) {
            e.printStackTrace();
            return "获取失败";
        }
    }

    //根据地址获取经纬度
    public Map geocode(String address) throws IOException {
        OkHttpClient client = new OkHttpClient();

        String url = String.format("%s?address=%s&output=json&key=%s",
                GEOCODING_URL, address, GAODE_API_KEY);

        Request request = new Request.Builder()
                .url(url)
                .build();
        String jsonResult = "";
        try (Response response = client.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                throw new IOException("Unexpected code " + response);
            }

            jsonResult = response.body().string();
        }
        try {
            JSONObject jsonObject = new JSONObject(jsonResult);
            int status = jsonObject.optInt("status");
            if (status == 1) { // 成功
                JSONArray geocodes = jsonObject.getJSONArray("geocodes");
                if (geocodes.length() > 0) {
                    JSONObject geocode = geocodes.getJSONObject(0);
                    String formattedAddress = geocode.getString("formatted_address");

                    // 正确解析 location 字段
                    String locationStr = geocode.getString("location");
                    String[] locationParts = locationStr.split(",");
                    if (locationParts.length == 2) {
                        double longitude = Double.parseDouble(locationParts[0]);
                        double latitude = Double.parseDouble(locationParts[1]);
                        Map ma = new HashMap();
                        ma.put("longitude",longitude);
                        ma.put("latitude",latitude);
                        return ma;
                    } else {
                        System.out.println("No geocoding results found.");
                        return null;
                    }
                }
            } else {
                return null;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
        return null;
    }

    //根据两个经纬度获取两个点的距离
    public double getDistance(double lat1, double lon1, double lat2, double lon2) {
        double earthRadius = 6371; // 地球半径，单位为公里

        double dLat = Math.toRadians(lat2 - lat1);
        double dLon = Math.toRadians(lon2 - lon1);

        double a = Math.sin(dLat / 2) * Math.sin(dLat / 2) +
                Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
                        Math.sin(dLon / 2) * Math.sin(dLon / 2);
        double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
        double distance = earthRadius * c;
        return distance;
    }
}
